package com.yz.system.UI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ClientChatFrame extends JFrame {
    public JTextArea smsContent = new JTextArea(23, 50);
    private JTextArea smsSend = new JTextArea(4, 40);
    public JList<String> onLineUsers = new JList<>();
    private JButton sendBn = new JButton("发送");
    private String nickname;
    private Socket socket;
    private JPopupMenu userPopupMenu;  // 添加一个JPopupMenu

    public ClientChatFrame() {
        initView();
        this.setVisible(true);
    }

    public ClientChatFrame(String nickname, Socket socket) {
        this();
        this.setTitle(nickname);
        this.socket = socket;
        // 立即把客户端的这个socket管道交给一个独立的线程专门负责读取socket从服务端收到的在线人数更新数据或者群聊数据
        new ClientReaderThread(socket, this).start();
    }

    private void initView() {
        this.setSize(700, 600);
        this.setLayout(new BorderLayout());
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口，退出程序
        this.setLocationRelativeTo(null); // 窗口居中

        // 设置窗口背景色
        this.getContentPane().setBackground(new Color(0xf0, 0xf0, 0xf0));

        // 设置字体
        Font font = new Font("SimKai", Font.PLAIN, 14);

        // 消息内容框
        smsContent.setFont(font);
        smsContent.setBackground(new Color(0xdd, 0xdd, 0xdd));
        smsContent.setEditable(false);

        // 发送消息框
        smsSend.setFont(font);
        smsSend.setWrapStyleWord(true);
        smsSend.setLineWrap(true);

        // 在线用户列表
        onLineUsers.setFont(font);
        onLineUsers.setFixedCellWidth(120);
        onLineUsers.setVisibleRowCount(13);

        // 初始化右键菜单
        initPopupMenu();

        // 添加鼠标监听器，用于右键点击用户时显示弹出菜单
        onLineUsers.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    int index = onLineUsers.locationToIndex(e.getPoint()); // 获取右键点击的位置
                    if (index != -1) {
                        onLineUsers.setSelectedIndex(index); // 选中右键点击的用户
                        userPopupMenu.show(onLineUsers, e.getX(), e.getY()); // 显示弹出菜单
                    }
                }
            }
        });

        // 创建底部面板
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setBackground(new Color(0xf0, 0xf0, 0xf0));

        // 消息输入框
        JScrollPane smsSendScrollPane = new JScrollPane(smsSend);
        smsSendScrollPane.setBorder(BorderFactory.createEmptyBorder());
        smsSendScrollPane.setPreferredSize(new Dimension(500, 50));

        // 发送按钮
        sendBn.setFont(font);
        sendBn.setBackground(Color.decode("#009688"));
        sendBn.setForeground(Color.WHITE);

        // 按钮面板
        JPanel btns = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        btns.setBackground(new Color(0xf0, 0xf0, 0xf0));
        btns.add(sendBn);

        sendBn.addActionListener(e -> {
            String msg = smsSend.getText();
            smsSend.setText("");
            // 发送消息给服务端
            sendMsgtoServer(msg);
        });

        // 添加组件
        bottomPanel.add(smsSendScrollPane, BorderLayout.CENTER);
        bottomPanel.add(btns, BorderLayout.EAST);

        // 用户列表面板
        JScrollPane userListScrollPane = new JScrollPane(onLineUsers);
        userListScrollPane.setBorder(BorderFactory.createEmptyBorder());
        userListScrollPane.setPreferredSize(new Dimension(120, 500));

        // 中心消息面板
        JScrollPane smsContentScrollPane = new JScrollPane(smsContent);
        smsContentScrollPane.setBorder(BorderFactory.createEmptyBorder());

        // 添加所有组件
        this.add(smsContentScrollPane, BorderLayout.CENTER);
        this.add(bottomPanel, BorderLayout.SOUTH);
        this.add(userListScrollPane, BorderLayout.EAST);
    }

    // 初始化右键菜单的方法
    private void initPopupMenu() {
        userPopupMenu = new JPopupMenu(); // 创建右键菜单

        JMenuItem privateChatItem = new JMenuItem("私聊"); // 创建菜单项
        privateChatItem.addActionListener(e -> {
            String selectedUser = onLineUsers.getSelectedValue(); // 获取选中的用户名
            if (selectedUser != null) {
                startPrivateChat(selectedUser); // 开始私聊
            }
        });

        userPopupMenu.add(privateChatItem); // 将菜单项添加到弹出菜单中
    }

    // 私聊功能：可以打开新的窗口进行私聊
    private void startPrivateChat(String selectedUser) {
        JOptionPane.showMessageDialog(this, "开始与 " + selectedUser + " 私聊！", "私聊", JOptionPane.INFORMATION_MESSAGE);
        // 设置发送框的内容，自动加上 @selectedUser 作为前缀
        smsSend.setText("@" + selectedUser + " ");
        smsSend.requestFocus(); // 聚焦到发送框，方便用户输入
    }


    private void sendMsgtoServer(String msg) {
        try {
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

            if (msg.startsWith("@")) { // 如果是私聊消息，格式为 "@username 消息内容"
                dos.writeInt(3); // 3代表私聊
                dos.writeUTF(msg); // 格式: "@username message"

                // 自己也显示这条消息
                String targetUser = msg.split(" ")[0].substring(1); // 获取目标用户名
                String messageContent = msg.split(" ", 2)[1]; // 获取消息内容
                sendMsg("私聊给 " + targetUser + ": " + messageContent);
            } else {
                dos.writeInt(2); // 2代表群聊
                dos.writeUTF(msg); // 群聊消息内容
            }
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }





    public void updateOnlineUsers(String[] onLineNames) {
        onLineUsers.setListData(onLineNames);
    }

    public void sendMsg(String msg) {
        smsContent.append(msg + "\n");
    }
}
